﻿using System;
using System.Collections.Generic;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Xml;
using Utility;
using File = System.IO.File;

namespace _411Client.HTML
{
    class HtmlPage
    {
        //HTML页面
        private readonly XmlDocument _html = new XmlDocument();

        //临时文件位置
        private readonly string _file = String.Format(Environment.GetEnvironmentVariable("TEMP") + "/411Chat/chating-{0}.html",Guid.NewGuid());

        //临时文件
        private readonly List<string> _tempFiles;

        /// <summary>
        /// 初始化
        /// </summary>
        public HtmlPage()
        {
            _html.LoadXml(String.Format(
                "<?xml version=\"1.0\"?><html><head><meta http-equiv=\"Content-Type\" content=\"text/html\" charset=\"utf-8\" /></head><body onload=\"document.body.scrollTop=document.body.scrollHeight\" style=\"background:url({0}) no-repeat fixed center\"></body></html>",
                Path.GetFullPath("App_Themes/bg.jpg")));
            if(!Directory.Exists(Environment.GetEnvironmentVariable("TEMP") + "/411Chat/"))
            {
                Directory.CreateDirectory(Environment.GetEnvironmentVariable("TEMP") + "/411Chat/");
            }
            File.Create(_file).Close();
            _tempFiles = new List<string> {_file};
        }

        /// <summary>
        /// 保存
        /// </summary>
        public void Save()
        {
            XmlNode body = _html.GetElementsByTagName("html")[0];
            string html = Replace(body.OuterXml);
            FileStream fs = File.OpenWrite(_file);
            byte[] bs = Encoding.UTF8.GetBytes(html);
            fs.Write(bs, 0, bs.Length);
            fs.Close();
        }

        /// <summary>
        /// 添加用户信息
        /// </summary>
        /// <param name="userName"></param>
        /// <param name="isMine"></param>
        public void AddUserInfo(string userName, bool isMine)
        {
            //用户信息
            XmlElement user = _html.CreateElement("div");
            user.SetAttribute("style", String.Format("margin-top:7px;font-size:12px;font-family:微软雅黑;color:{0}", isMine ? "blue" : "green"));
            XmlText userInfo = _html.CreateTextNode(String.Format("{0}  {1}", userName, DateTime.Now));
            user.AppendChild(userInfo);

            XmlNode body = _html.GetElementsByTagName("body")[0];
            body.AppendChild(user);
        }

        /// <summary>
        /// 添加消息
        /// </summary>
        /// <param name="message"></param>
        public void AddMessage(Message message)
        {
            //消息
            XmlElement msg = _html.CreateElement("div");
            msg.SetAttribute("style",
                             String.Format(
                                 "margin-top:5px;margin-left:10px;font-family:{0};font-size:{1}px;color:rgb({2},{3},{4})",
                                 message.FontFamily, message.FontSize, message.FontColor.R, message.FontColor.G,
                                 message.FontColor.B));
            XmlText content = _html.CreateTextNode(message.Content);
            msg.AppendChild(content);

            XmlNode body = _html.GetElementsByTagName("body")[0];
            body.AppendChild(msg);
        }

        /// <summary>
        /// 添加图片
        /// </summary>
        /// <param name="image"></param>
        public void AddImage(Images image)
        {
            string fileName = String.Format(Environment.GetEnvironmentVariable("TEMP") + "/411Chat/{0}.{1}",
                                            Guid.NewGuid(), image.Extension);
            FileStream fs = File.OpenWrite(fileName);
            fs.Write(image.FileContent, 0, image.FileContent.Length);
            fs.Close();
            //图片
            AddImage(fileName); 
            _tempFiles.Add(fileName);
        }

        /// <summary>
        /// 添加图片
        /// </summary>
        public void AddImage(string path)
        {
            //图片
            XmlElement img = _html.CreateElement("img");
            img.SetAttribute("src", path);
            img.SetAttribute("onload", "this.width=this.width>450?450:this.width;");
            img.SetAttribute("style", "margin-top:5px;margin-left:10px;");

            XmlNode body = _html.GetElementsByTagName("body")[0];
            body.AppendChild(img);
        }

        /// <summary>
        /// 获取路径
        /// </summary>
        /// <returns></returns>
        public string GetUrlString()
        {
            return _file;
        }

        /// <summary>
        /// 删除所有聊天文件
        /// </summary>
        public void DeleteChatFiles()
        {
            foreach(string file in _tempFiles)
            {
                File.Delete(file);
            }
        }

        //替换表情
        private string Replace(string s)
        {
            string res = s;
            string path = Path.GetFullPath("App_Themes/");
            for (int i = 1; i < 5;i++ )
            {
                for (int j = 1; j < 9; j++)
                {
                    res = res.Replace(String.Format("&#x{0};&#x{1};", i, j),
                                      String.Format("<img src=\"{0}{1}{2}.gif\" />", path, i, j));
                }
            }

            return res.Replace("\n", "<br/>");
        }
    }
}
